package com.qy139.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class MyAuthenticationFailtureHandler implements AuthenticationFailureHandler {
    @Resource
    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        Map m=new HashMap<>();
        m.put("code",408);
        m.put("msg","认证失败！！！");
        m.put("data",null);

        //json数据    uft-8
        response.setContentType("application/json;charset=utf8");
//json字符串
        String m1=objectMapper.writeValueAsString(m);
        //
        PrintWriter out = response.getWriter();
        out.write(m1);
        out.flush();
        out.close();
    }
}
